import cn.edu.dgut.Javabean_object.Person;
import cn.edu.dgut.Javabean_object.register;


import javax.json.Json;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/checkServlet")
public class checkServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EntityManager em = (EntityManager) request.getAttribute("_entity.manager");
            String pathname = "userinfo.txt";
            FileReader reader = new FileReader(pathname);
            BufferedReader br = new BufferedReader(reader);

            String line;
            String aa= request.getParameter("user_name");
            String bb= request.getParameter("password");
            Person personer=em.find(Person.class,aa);
            int flag=0;
            if(personer==null)   response.sendRedirect("/login.jsp");
            else {
                if (personer.getPassword().equals(bb)) {
                    flag = 1;
                }
           /* while ((line = br.readLine()) != null) {
                // 一次读入一行数据
                System.out.println(line);
                response.getWriter().println(line);
                Jsonb json = JsonbBuilder.create();
                register person=json.fromJson(line,register.class);
                String a=person.getUser_number();
                String b=person.getPassword();
                if(a!=null&&b!=null) {
                    if (a.equals(aa) && b.equals(bb)) flag = 1;
                }

            }
        */
                if (flag == 1) {
                    Map<String, String> message = new HashMap<String, String>();
                    message.put("user_number", aa);
                    message.put("name", bb);
                    HttpSession session = request.getSession(true);
                    session.setAttribute("Login", message);
                    response.sendRedirect("/userInfo.jsp");
                } else {
                    response.sendRedirect("/error.jsp");

                }
            }
        }



}
